import csv
import random
import sys, os
import time
import datetime
import pdb

start_words = {}
word_dic = {}
word_list = []

next_start_page = 0
next_num_page = 0
next_num_page = 0
num_last_problem = 0
num_problem = 0
str_ratio_difficult = ""
last_updated = ""

data_file = "data2.csv"

def MakeStartWordDic():
    global start_words, word_dic
    
    reader = csv.reader(open("korgre_pages.csv"))
    for page, start_word in reader:
        start_word = start_word.upper()
        start_words[int(page)] = start_word

def init():
    global word_dic, word_list
    
    f = open(data_file)
    reader = csv.reader(f)
    for word, meaning, level, numquestion, numwrong in reader:
        word = word.upper()
        word_dic[word] = (meaning, int(level), int(numquestion), int(numwrong))
        word_list.append(word)

    MakeStartWordDic()
    f.close()

def difficult(word):
    global word_dic
    if word_dic[word][2] > 0 and word_dic[word][3] == 0:
        return False
    return ( (word_dic[word][1] == 1 or word_dic[word][1] == 2) and True or False )
    
def easy(word):
    return not difficult(word)

def MakeProblem(high_problems, low_problems, numProblems, ratio_difficult):
    len_high = len(high_problems)
    len_low = len(low_problems)
    print "len_high : %d, len_low: %d"%(len_high, len_low)

    ratio = float(len_high) / float(len_low + len_high)

    num_high = int (numProblems * ratio_difficult)
    print "num_high: %d"%num_high
    random.shuffle(low_problems)
    random.shuffle(high_problems)
    
    #prioritize by numQuestion
    #pdb.set_trace()
    
    if ratio > ratio_difficult:
        num_high = int(numProblems * ratio)
        problems = high_problems[0:num_high]
        problems.extend(low_problems[0:(numProblems-num_high)])
        
    elif len_high < num_high:
        problems = high_problems
        problems.extend(low_problems[0:(numProblems-len_high)])

    else:
        random.shuffle(high_problems)
        problems = high_problems[0:num_high]
        low_problems = low_problems[0:(numProblems - num_high)]
        problems.extend(low_problems)

    random.shuffle(problems)
    return problems
    
def GetWordList(start, end):
    global word_list, start_words
    words = []
    if start < 3:
        start = 3
    if start > 235:
        start = 235
        
    if end > 235:
        end = 235
    if end < 3:
        end = 3

    if start > end:
        a = GetWordList(start, 235)
        a.extend(GetWordList(3, end))
        random.shuffle(a)
        return a

    #pdb.set_trace()
    start_index = word_list.index(start_words[start])
    if end != 235:
        end_index = word_list.index(start_words[end + 1])
    else:
        end_index = len(word_list)
    
    #print "start: %d - %d" % (start, start_index)
    #print "end  : %d - %d" % (end, end_index)

    problems = word_list[start_index: end_index]
    random.shuffle(problems)
    
    return problems

def GetNextPlan():
    global next_start_page, next_num_page, next_num_page, num_last_problem
    global num_problem, str_ratio_difficult, last_updated

    f = open("last_log.txt", "r")
    last_log = f.readline().split()
    f.close()
    if len(last_log) < 8:
        return (0, 0, 0, 0, 0, 0.0)
    last_start_page = int(last_log[0])
    last_num_page = int(last_log[1])
    next_num_page = int(last_log[2])
    num_last_problem = int(last_log[3])
    num_problem = int(last_log[4])
    str_ratio_difficult = last_log[5]
    last_question = last_log[6]
    last_updated = last_log[7]
    ratio_difficult = float(str_ratio_difficult)

    if last_question != last_updated:
        return None

    if last_start_page + last_num_page > 235:
        next_start_page = last_start_page + last_num_page - 233
    else:
        next_start_page = last_start_page + last_num_page

    if next_start_page + next_num_page > 235:
        next_end_page = next_start_page + next_num_page - 234
    else:
        next_end_page = next_start_page + next_num_page - 1

    return (last_start_page, next_start_page, next_end_page, num_last_problem,  num_problem, ratio_difficult)
    
if __name__ == "__main__":
    init()
    if len(sys.argv) >= 6:
        last_start_page = int(sys.argv[1])
        start_page = int(sys.argv[2])
        end_page = int(sys.argv[3])
        num_last_problem = int(sys.argv[4])
        num_problem = int(sys.argv[5])
        ratio_difficult = 1.0
    else:
        temp = GetNextPlan()
        if temp == None:
            print "not updated"
            sys.exit(0)
            
        last_start_page = temp[0]
        start_page = temp[1]
        end_page = temp[2]
        num_last_problem = temp[3]
        num_problem = temp[4]
        ratio_difficult = temp[5]
            
    wl = GetWordList(start_page, end_page)
    wl_last = GetWordList(last_start_page, start_page > 3 and start_page - 1 or 235)
    
    historic_problems = filter( lambda x: word_dic[x][1] > 2, word_list)
    
    high_problems = filter(difficult, wl)
    low_problems = filter(easy, wl)
    print "Current Range..."
    p1 = MakeProblem(high_problems, low_problems, num_problem, ratio_difficult)

    if num_last_problem > 0:
        print "Lastday Range..."
        high_problems_last = filter(difficult, wl_last)
        low_problems_last = filter(easy, wl_last)
        p2 = MakeProblem(high_problems_last, low_problems_last, num_last_problem, ratio_difficult)
    else:
        p2 = []

    len_historic = len(historic_problems)
    new_problems = p1
    new_problems.extend(p2)
    problems = historic_problems
    problems.extend(new_problems)
    random.shuffle(problems)

    answers = [word_dic[w][0] for w in problems]
    
    file_problem = open("problem.txt", "w")
    file_answer = open("answer.txt", "w")
    
    file_problem.write("%d - %d\n\n"%(start_page, end_page))
    for i in range(0, num_problem + num_last_problem + len_historic):
        file_problem.write("%d. %s\n" %((i+1), problems[i]))
        file_answer.write("%d. %s\t%s\n"% (i+1, problems[i], answers[i]))
        old_val = word_dic[problems[i]]
        word_dic[problems[i]] = (old_val[0], old_val[1], old_val[2]+1, old_val[3])

    file_problem.close()
    file_answer.close()

    f = open(data_file, "w")
    writer = csv.writer(f)
    for word in word_list:
        value = word_dic[word]
        pair = (word, value[0], value[1], value[2], value[3])
        writer.writerow(pair)

    
    f = open("last_log.txt", "w")
    f.write("%d %d %d %d %d %s %s %s" %(next_start_page, next_num_page, next_num_page, num_last_problem, num_problem, str_ratio_difficult, problems[0], last_updated))
    f.close()

    if len(sys.argv) < 6:
        os.system("problem.txt")
 #       os.system("gre_word.au3 " + "\"%s Vocabulary (p.%d - p.%d)\""% (str(datetime.date.today() + datetime.timedelta(1)), start_page, end_page))
    else:
        time = datetime.date.today() + datetime.timedelta(1)
        problem = "%d%02d%02d-Problem"%(time.year, time.month, time.day)
        answer = "%d%02d%02d-Answer"%(time.year, time.month, time.day)
        problem = problem[2:]
        answer = answer[2:]
        
        os.system("gre_orinemo.au3 " + "\"http://orinemo.cafe24.com/moniwiki/wiki.php/GREStudy/%s?action=edit\" \"http://orinemo.cafe24.com/moniwiki/wiki.php/GREStudy/%s?action=edit\""% (problem, answer))

